package com.cn.xc.utils;

import java.util.Date;

import org.apache.commons.lang.math.NumberUtils;

/**
 * FUN: Object type convert tools class
 *
 * @author sushy
 * @date 2016-3-23 
 */
public class ObjectUtil {

	public final static String EMPTY_STR = "";

	/**
	 *  //# convert to java.uitl.date
	 * 
	 * @param obj
	 * @return
	 */
	public static Date toDate(Object obj) {
		if (obj == null) {
			return null;// null默认返回值
		}
		if (obj instanceof Date) {
			return (Date) obj;
		}

		if (obj instanceof String) {
			return DateUtil.str2Date((String) obj);
		}

		return null;// failed
	}

	/**
	 *  //# convert to int
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static int toInt(Object obj) {
		return toInt(obj, 0);
	}

	/**
	 * //# convert to int, include defalut value
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static int toInt(Object obj, int defaultValue) {
		if (obj == null) {
			return defaultValue;
		}
		if (obj instanceof Number) {
			return ((Number) obj).intValue();
		}
		return NumberUtils.toInt(obj.toString(), defaultValue);
	}

	/**
	 * //# convert to long
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long toLong(Object obj) {
		return toLong(obj, 0);
	}

	/**
	 * //# convert to long, include defalut value
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long toLong(Object obj, long defaultValue) {
		if (obj == null) {
			return defaultValue;
		}
		if (obj instanceof Number) {
			return ((Number) obj).longValue();
		}
		return NumberUtils.toLong(obj.toString(), defaultValue);
	}

	/**
	 * //# convert to double
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static double toDouble(Object obj) {
		return toDouble(obj, 0);
	}

	/**
	 * //# convert to Double,include defalut value
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static double toDouble(Object obj, double defaultValue) {
		if (obj == null) {
			return defaultValue;
		}
		if (obj instanceof Number) {
			return ((Number) obj).doubleValue();
		}
		return NumberUtils.toDouble(obj.toString(), defaultValue);
	}

	/**
	 * //# convert to String
	 * 
	 * @param obj
	 * @return
	 */
	public static String toString(Object obj) {
		return toString(obj, EMPTY_STR);
	}

	/**
	 * //# convert to String, include defalut value
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String toString(Object obj, String defaultValue) {
		if (obj == null) {
			return defaultValue;
		}

		String value = null;
		if (obj instanceof String) {
			value = (String) obj;
		} else if (obj instanceof Date) {
			value = DateUtil.date2Str((Date) obj);
		} else {
			value = obj.toString();
		}

		return value == null ? defaultValue : value;
	}

}
